package com.bianmaba.beans.datacollection;

import com.bianmaba.spring.data.jpa.domain.entity.UuidIdentityEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.Date;

@Entity
@Data
@DynamicUpdate(true)
@DynamicInsert(true)
@AllArgsConstructor
@NoArgsConstructor
public class TaskInstance extends UuidIdentityEntity {

    @Column()
    private String name;
    @Column(name = "[group]")
    private String group;
    @Column()
    private Date startTime;
    @Column()
    private Date endTime;
    @Column()
    private Integer status = Status.WAIT.getIndex();
    @Column()
    private String executor;

    @ManyToOne(optional = false)
    @JoinTable(name = "TaskInstance_ref_CollectionTask")
    private CollectionTask collectionTask;

    public static TaskInstance of(String taskId) {
        TaskInstance task = new TaskInstance();
        task.setId(taskId);
        return task;
    }

    public static enum Status {
        UNKNOWN("未知", -1),
        WAIT("待执行", 1),
        RUNNING("执行中", 2),
        SUCCESSFUL("已完成", 3),

        UNSUCCESSFUL("失败", 4),
        EXCEPTIONAL("异常", 5),
        TERMINATED("终止", 6);

        // 成员变量
        private String name;
        private int index;

        // 构造方法
        Status(String name, int index) {
            this.name = name;
            this.index = index;
        }

        public String getName() {
            return name;
        }

        public int getIndex() {
            return index;
        }

        // 普通方法
        public static String getName(int index) {
            for (Status result : values()) {
                if (result.getIndex() == index) {
                    return result.getName();
                }
            }
            return null;
        }

        public static Integer getIndex(String name) {
            for (Status item : values()) {
                if (item.getName().equals(name)) {
                    return item.getIndex();
                }
            }
            return -1;
        }

        public static Status get(int index) {
            for (Status item : values()) {
                if (item.getIndex() == index) {
                    return item;
                }
            }
            return UNKNOWN;
        }

        public static Status get(String name) {
            for (Status item : values()) {
                if (item.getName().equals(name)) {
                    return item;
                }
            }
            return UNKNOWN;
        }
    }
}
